package com.boot.security.server.utils;




import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;



/**
 * @author: Ming
 * @date: 2019/12/11 14:17
 * @description: 实体类与封装类Dto转换工具 注：转换类字段必须与实体类一致
 */

public class BeanHelper {
    //入参 需要转换的类，需要转换的类型
    public static <T> T copyProperties(Object source, Class<T> target) {
        try {
            T t = target.newInstance();
            BeanUtils.copyProperties(source, t);
            return t;
        } catch (Exception e) {
            System.out.println("数据转换异常" + target.getName() + e);
            throw new RuntimeException(e);

        }
    }

    public static <T> List<T> copyWithCollection(List<?> sourceList, Class<T> target) {
        try {
            return sourceList.stream().map(s -> copyProperties(s, target)).collect(Collectors.toList());
        } catch (Exception e) {
            System.out.println("数据转换异常" + target.getName() + e);
            throw new RuntimeException(e);

        }
    }

    public static <T> Set<T> copyWithCollection(Set<?> sourceList, Class<T> target) {
        try {
            return sourceList.stream().map(s -> copyProperties(s, target)).collect(Collectors.toSet());
        } catch (Exception e) {
            System.out.println("数据转换异常" + target.getName() + e);
            throw new RuntimeException(e);

        }
    }
}
